package com.efounder.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.alibaba.fastjson.JSON;
import com.allen.library.SuperTextView;
import com.efounder.activity.Order.CreateOrderAdapter;
import com.efounder.activity.Order.OrderPreAdapter;
import com.efounder.bean.*;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.holder.BaseHolder;
import com.efounder.holder.OrderPreHolder;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.DialogUtil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.CustomDatePicker;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.MyMathUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.pop.MPopuWindow;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.utilcode.util.TimeUtils;
import com.utilcode.util.ToastUtils;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.efounder.activity.ProductDetailsActivity.GOOD_TYPE_NEW_VIRTUAL;
import static com.efounder.activity.ProductDetailsActivity.GOOD_TYPE_VIRTUAL;
import static com.efounder.utils.MallRequestUtil.ADDRESS_LIST_URL;
import static com.efounder.utils.MallRequestUtil.ORDER_CREATE_URL;

/**
 * Created by will on 18-3-6.
 * 商城订单确认
 */

public class CreateOrderActivity extends BaseActivity implements View.OnClickListener {

    private List<Address> addresses = new ArrayList<>();
    private Address defaultAddress;
    private Address targetAddress = null;
    private EditText etCustomerNote;
    private double allPrice;
    private String orderTitle = "";
    private static final int CHOOSE_ADDRESS_REQUEST_CODE = 8801;
    private static final int ADD_ADDRESS_REQUEST_CODE = 8802;
    private int TIME_TYPE = 0X01;
    private static final int TIME_TYPE_MAIL = 0X01;
    private static final int TIME_TYPE_YOUR = 0X02;


    private Address address1;
    private CustomDatePicker timePicker;
    private String currentDate;
    private RecyclerView recyclerView;
    private ImageView ivBack;
    private TextView tvTitle;
    private TextView tvName;
    private TextView tvAddress;
    private TextView tvPhone;
    private TextView tvCreateOrder;
    private List<TextView> textViews = new ArrayList<>();
    private ConstraintLayout clAddress;
    private ConstraintLayout clNoAddress;
    private LinearLayout orderLlContent;
    private RecyclerView orderRlvPre;

    private MPopuWindow popuWindow;
    private OrderInfoBean cartBean;
    private String goods;
    private List<OrderInfoBean.DataBean.ShopsBean> mShops;
    private CreateOrderAdapter mAdapter;
    private List<OrderInfoBean.DataBean.PreOrderDiscountBean> mPres;
    private OrderPreAdapter preAdapter;
    private Map<Integer, OrderPreBean> preJa;
    private double prePrice;
    private boolean IS_CREAT_ORDER;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mall_activity_create_order);
        goods = getIntent().getStringExtra("checkItems");

        preJa = new HashMap<>();
        initView();
    }


    private void initView() {
        if (textViews.size() != 0) {
            textViews.clear();
        }
        recyclerView = (RecyclerView) findViewById(R.id.rl_item_view);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvPhone = (TextView) findViewById(R.id.tv_phone);
        tvCreateOrder = (TextView) findViewById(R.id.tv_create_order);
        textViews.add((TextView) findViewById(R.id.order_item_count));
        textViews.add((TextView) findViewById(R.id.tv_amount_total));
        textViews.add((TextView) findViewById(R.id.tv_order_total));
        clAddress = (ConstraintLayout) findViewById(R.id.cl_address);
        clNoAddress = (ConstraintLayout) findViewById(R.id.cl_no_address);
        orderLlContent = (LinearLayout) findViewById(R.id.order_ll_content);
        orderRlvPre = (RecyclerView) findViewById(R.id.order_rlv_pre);

        ivBack.setOnClickListener(this);
        tvTitle.setText(R.string.mail_sure_order);
        clAddress.setOnClickListener(this);
        clNoAddress.setOnClickListener(this);
        tvCreateOrder.setOnClickListener(this);
        etCustomerNote = (EditText) findViewById(R.id.et_customer_note);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        mShops = new ArrayList<>();
        mAdapter = new CreateOrderAdapter(mShops);
        recyclerView.setAdapter(mAdapter);
        //优惠信息
        orderRlvPre.setLayoutManager(new LinearLayoutManager(this));
        mPres = new ArrayList<>();
        preAdapter = new OrderPreAdapter(mPres);
        orderRlvPre.setAdapter(preAdapter);
        getPrepareOrder(goods);
        mAdapter.setOnOrderStoreInfoHolderListener(new CreateOrderAdapter.OnOrderStoreInfoHolderListener() {

            @Override
            public void onSelectExpress(View v, int position) {//选择运输方式
//                selectExpress(position);


            }

            @Override
            public void onChildItemClick(BaseHolder holder, int childPos, int pos) {
                Intent intent = new Intent(CreateOrderActivity.this, ProductDetailsActivity.class);
                intent.putExtra("goodbh", cartBean.getData().getShops().get(pos).getGoods().get(childPos).getGoodId());
                startActivity(intent);
            }
        });
        preAdapter.setOnOrderPreHolderListener(new OrderPreAdapter.OnOrderPreHolderListener() {
            @Override
            public void onPreferentChange(OrderPreHolder holder, double i, int position) {//优惠
                //数量改变
                OrderInfoBean.DataBean.PreOrderDiscountBean preOrderDiscountBean = mPres.get(position);
                double i1 = Double.parseDouble(preOrderDiscountBean.getDiscountRatio());
                if (i / i1 > cartBean.getData().getGoodTotalMoney()) {
                    ToastUtil.showToastCenter(getResources().getString(R.string.mall_out_of_pre));
                } else {
                    holder.getOrderTvChangeNum().setText(i + "");
                    BigDecimal decimal = MyMathUtil.round3(i / i1, 2);
                    String oldPre = holder.getOrderTVmoney().getText().toString().trim();//上一次优惠金额
                    double parseDouble = Double.parseDouble(oldPre);
                    allPrice -= (decimal.doubleValue() - parseDouble);
                    holder.setMoneyChange(i + "");
                    OrderPreBean bean = preJa.get(position);
                    if (bean != null) {
                        bean.setAmount(i);
                    }
                    setPriceTotal();
                }
//                }

            }

            @Override
            public void onCheckboxChanged(CompoundButton buttonView, boolean isChecked, int pos, OrderPreHolder holder) {
                if (isChecked) {
                    holder.updateMoney();
                    //查询用户有多少
                    queryUserPreInfo(pos, buttonView, holder);
                } else {
                    holder.setLinelayout(View.GONE);
                    synchronized (this) {
                        preJa.remove(pos);
                        String trim = holder.getOrderTVmoney().getText().toString().trim();
                        allPrice += Double.parseDouble(trim);
                        setPriceTotal();
                    }
                }
            }
        });

    }

    //查询用户银钻等余额
    private void queryUserPreInfo(final int pos, final CompoundButton buttonView, final OrderPreHolder holder) {
        LoadingDataUtilBlack.show(this, getResources().getString(R.string.mall_query_pre_info));
        HashMap<String, String> map = new HashMap<>();
        map.put("phoneNumber", EnvironmentVariable.getUserName());
        map.put("cardId", mPres.get(pos).getDiscountTypeId());
        MallRequestUtil.getRequest(TAG, MallRequestUtil.QUERY_USER_BALANCE, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                UserBanlanceInfo banlanceInfo = new Gson().fromJson(response, UserBanlanceInfo.class);
                if ("success".equals(banlanceInfo.getResult()) && banlanceInfo.getData() != null) {
                    UserBanlanceInfo.DataBean data = banlanceInfo.getData();
//                    data.setBalance(5+"");
                    double hasAmount = Double.valueOf(data.getBalance());//有多少
                    if (hasAmount > 0) {
                        holder.setLinelayout(View.VISIBLE);
                        haveBalance(hasAmount, pos, holder);
                    } else {
                        userNoBalance(buttonView, String.format(getResources().getString(R.string.pre_not_enought), mPres.get(pos).getDiscountTypeName()), holder);
                    }

                } else {
                    userNoBalance(buttonView, getResources().getString(R.string.mail_get_data_fail_again), holder);
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                userNoBalance(buttonView, getResources().getString(R.string.mail_get_data_fail_again), holder);
            }
        });
    }

    private void haveBalance(double hasAmount, int pos, OrderPreHolder holder) {
        double ratio = Double.valueOf(mPres.get(pos).getDiscountRatio());
        double atMostAmount = mPres.get(pos).getAtMostAmount();//最多使用

//                    if (allPrice < atMostAmount/ratio) {
        //目前不存在优惠大于商品金额的情况
//                        holder.setMoneyChange(Math.floor(allPrice) + "");
//                        holder.getOrderTvChangeNum().setText(Math.floor(allPrice) * ratio + "");
//                        allPrice -= Math.floor(allPrice);
//                    }
        OrderPreBean bean = new OrderPreBean();
        bean.setTypeId(Integer.parseInt(mPres.get(pos).getDiscountTypeId()));//记录优惠信息
        mPres.get(pos).setHasAmount(hasAmount);//设置有多少
        if (hasAmount > atMostAmount) {
            //最多使用优惠
            allPrice -= (atMostAmount / ratio);
            bean.setAmount(atMostAmount);
            //设置优惠信息
            holder.setMoneyChange(atMostAmount + "");
            holder.getOrderTvChangeNum().setText(atMostAmount + "");
        } else {
            allPrice -= (hasAmount / ratio);
            bean.setAmount(hasAmount);
            holder.setMoneyChange(hasAmount + "");
            holder.getOrderTvChangeNum().setText(hasAmount + "");
        }
        preJa.put(pos, bean);
        setPriceTotal();
    }

    private void userNoBalance(CompoundButton buttonView, String error, OrderPreHolder holder) {
        holder.setLinelayout(View.GONE);
        buttonView.setChecked(false);
        DialogUtil.showDialogNoCancel(this, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }, R.string.dialog_title_defalut, error, getResources().getString(R.string.mall_sure));

    }


    private void selectExpress(int position) {
        initTimePicker();//初始化日期控件
        popuWindow = new MPopuWindow(this);
        List<String> express = new ArrayList<>();
        express.add(ResStringUtil.getString(R.string.mall_address_mailing));
        express.add(ResStringUtil.getString(R.string.mall_address_pick_store));
        popuWindow.setRGInfo(express).setTextViewTime(currentDate)
                .setEditTextTel(address1.getPhone()).setSurperTextTime(currentDate);
        popuWindow.showPopupWindow(orderLlContent);

        popuWindow.setPopupWindowListener(new MPopuWindow.MPopupWindowListener() {
            @Override
            public void selectDate(TextView textView) {//选择时间
                TIME_TYPE = TIME_TYPE_MAIL;
                timePicker.show(currentDate);
            }

            @Override
            public void selectDate(SuperTextView superTextView) {
                TIME_TYPE = TIME_TYPE_YOUR;
                timePicker.show(currentDate);
            }

            @Override
            public void clickSure(String time, String phone, int type) {

            }

        });

    }

    private void setPriceTotal() {
        BigDecimal bd = new BigDecimal(allPrice);
        BigDecimal bigDecima = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        textViews.get(1).setText(cartBean.getData().getShops().get(0).getGoods().get(0).getMallGoodPrice().getPriceUnit() + " " + bigDecima);
        textViews.get(2).setText(cartBean.getData().getShops().get(0).getGoods().get(0).getMallGoodPrice().getPriceUnit() + " " + bigDecima);
    }

    private void initTimePicker() {
        currentDate = TimeUtils.millis2String(System.currentTimeMillis(), new SimpleDateFormat("yyyy-MM-dd"));
        String endDate = TimeUtils.millis2String(System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000, new SimpleDateFormat("yyyy-MM-dd"));
        timePicker = new CustomDatePicker(this, getResources().getString(R.string.mall_select_time), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                if (TIME_TYPE == TIME_TYPE_MAIL) {
                    if (popuWindow != null) {
                        popuWindow.setSurperTextTime(time);
                    }
                } else {
                    popuWindow.setTextViewTime(time);
                }
            }

        }, currentDate, endDate);//"2027-12-31 23:59"
        timePicker.showSpecificTime(false);
        timePicker.setIsLoop(true);

    }


    private void initAddress(final String addressId) {
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, ADDRESS_LIST_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if ("success".equals(jsonObject.getString("result"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("addresses");
                        //
                        if (jsonArray.length() > 0) {
                            List<Address> adds = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<Address>>() {
                            }.getType());
                            addresses.clear();
                            addresses.addAll(adds);
                            for (Address add : adds) {
                                if ("1".equals(add.getIsSelected())) {
                                    defaultAddress = add;
                                }
                                if (addressId != null && addressId.equals(add.getAddressId())) {
                                    targetAddress = add;
                                }
                            }
                            setAddress(addressId);//设置地址
                        } else {
                            clAddress.setVisibility(View.GONE);
                            if (setAddressIsShow()) {
                                clNoAddress.setVisibility(View.GONE);
                            } else {
                                clNoAddress.setVisibility(View.VISIBLE);
                            }

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    clAddress.setVisibility(View.GONE);
                    if (setAddressIsShow()) {
                        clNoAddress.setVisibility(View.GONE);
                    } else {
                        clNoAddress.setVisibility(View.VISIBLE);
                    }
                }

            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToast(CreateOrderActivity.this, getResources().getString(R.string.network_anomalies));
            }
        });
    }

    private void setAddress(String addressId) {
        if (addresses.size() > 0) {
            if (setAddressIsShow()) {
                clAddress.setVisibility(View.GONE);
            } else {
                clAddress.setVisibility(View.VISIBLE);
            }

            clNoAddress.setVisibility(View.GONE);

            if (targetAddress == null) {
                if (defaultAddress != null) {
                    tvAddress.setText(defaultAddress.getArea() + " " + defaultAddress.getAddress());
                    tvName.setText(defaultAddress.getUserName());
                    tvPhone.setText(defaultAddress.getPhone());
                } else {
                    tvAddress.setText(addresses.get(0).getArea() + " " + addresses.get(0).getAddress());
                    tvName.setText(addresses.get(0).getUserName());
                    tvPhone.setText(addresses.get(0).getPhone());
                }
            } else {
                tvAddress.setText(targetAddress.getArea() + " " + targetAddress.getAddress());
                tvName.setText(targetAddress.getUserName());
                tvPhone.setText(targetAddress.getPhone());
            }
        } else {
            clAddress.setVisibility(View.GONE);
            if (setAddressIsShow()) {
                clNoAddress.setVisibility(View.GONE);
            } else {
                clNoAddress.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        //选择地址
        if (id == R.id.cl_address) {
            if (addresses.size() > 0) {
                Intent intent = new Intent(this, MallSelectAddressActivity.class);
                if (targetAddress != null) {
                    intent.putExtra("addressId", targetAddress.getAddressId());
                }

                startActivityForResult(intent, CHOOSE_ADDRESS_REQUEST_CODE);
            } else {
                Intent intent = new Intent(this, MallAddAddressNewActivity.class);
                startActivityForResult(intent, ADD_ADDRESS_REQUEST_CODE);
            }
        } else if (id == R.id.cl_no_address) {
            Intent intent = new Intent(this, MallAddAddressNewActivity.class);
            startActivityForResult(intent, ADD_ADDRESS_REQUEST_CODE);
        } else if (id == R.id.tv_create_order) {
            if (!IS_CREAT_ORDER) {
                getCreatOrder();
            }

        } else if (id == R.id.iv_back) {
            finish();
        }
    }

    private void getCreatOrder() {

        //如果订单信息为空，返回订单为空提示
        if (cartBean != null && cartBean.getData() == null) {
            ToastUtils.showShort(ResStringUtil.getString(R.string.mall_create_order_info_null));
            return;
        }

        //请求生成订单
        final HashMap<String, String> map = new HashMap<>();
        if (targetAddress != null) {
            map.put("addressId", targetAddress.getAddressId());
        } else if (defaultAddress != null) {
            map.put("addressId", defaultAddress.getAddressId());
        } else if (addresses.size() > 0) {
            map.put("addressId", addresses.get(0).getAddressId());
        } else {
//            ToastUtil.showToast(this, R.string.palse_check_address);
//            return;
            if (cartBean != null && (cartBean.getData().getShops().get(0).getGoods().get(0).getTypeBh().equals(GOOD_TYPE_VIRTUAL)
                    || cartBean.getData().getShops().get(0).getGoods().get(0).getTypeBh().equals(GOOD_TYPE_NEW_VIRTUAL))) {
                map.put("addressId", "");
            } else {
                ToastUtil.showToast(this, R.string.palse_check_address);
                return;
            }
        }
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("note", etCustomerNote.getText().toString());
        try {
            JSONObject object = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            for (OrderPreBean values : preJa.values()) {
                String s = new Gson().toJson(values);
                JSONObject jsonObject = new JSONObject(s);
                jsonArray.put(jsonObject);
            }

            object.put("discount", jsonArray);
            object.put("goods", goods);

            map.put("params", String.valueOf(object));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        IS_CREAT_ORDER = true;
        LoadingDataUtilBlack.show(this, getResources().getString(R.string.common_text_please_wait));
        MallRequestUtil.postRequest(TAG, ORDER_CREATE_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                IS_CREAT_ORDER = false;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if ("success".equals(jsonObject.getString("result"))) {
                        //通知更新角标
                        EventBus.getDefault().post(new UpdateOrderBadgeEvent());
                        BigDecimal bd = new BigDecimal(allPrice);
                        BigDecimal bigDecima = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                        JSONArray orderId = jsonObject.getJSONArray("orderIds");
                        List<String> strings = JSON.parseArray(orderId.toString(), String.class);
                        //如果两个订单提示跳转订单界面付款
                        if (showDialogPayHint(strings)) {
                            return;
                        }
                        orderTitle = mShops.get(0).getMallShop().getShopName();
                        //如果是夺宝的订单
                        if (1 == jsonObject.optInt("isSnatchOrder")) {
                            //跳夺宝支付界面
                            String goodsId = new JSONArray(goods).optJSONObject(0).optString("goodbh");
                            MallSelectionPayNoAliWxActivity.start(CreateOrderActivity.this,
                                    (ArrayList<String>) strings, goodsId, bigDecima + ""
                            );
                        } else {
                            //如果虚拟商品就跳虚拟商品的支付界面
                            if (mShops.get(0).getGoods().get(0).getTypeBh().equals(GOOD_TYPE_VIRTUAL)) {
                                String goodsId = new JSONArray(goods).optJSONObject(0).optString("goodbh");
                                MallVirtualProductSelectionPayActivity.start(CreateOrderActivity.this,
                                        (ArrayList<String>) strings, goodsId, bigDecima + "");
                            } else {
                                //跳普通支付
                                SelectionPayActivity.start(CreateOrderActivity.this, (ArrayList<String>) strings,
                                        bigDecima + "", orderTitle);
                            }

                        }
                        finish();
                    } else {
                        ToastUtil.showToast(CreateOrderActivity.this, jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    ToastUtil.showToast(CreateOrderActivity.this, getResources().getString(R.string.network_anomalies));
                }

            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToast(CreateOrderActivity.this, getResources().getString(R.string.network_anomalies));
                //todo
                IS_CREAT_ORDER = false;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CHOOSE_ADDRESS_REQUEST_CODE && resultCode == RESULT_OK) {
            String addressId = data.getExtras().getString("addressId");
            initAddress(addressId);
        } else if (requestCode == ADD_ADDRESS_REQUEST_CODE && resultCode == RESULT_OK) {
            initAddress(null);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }

    public void getPrepareOrder(String goods) {
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("goods", goods);
        Log.d(TAG, "getPrepareOrder: " + goods + EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, MallRequestUtil.PREPARE_ORDER_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                cartBean = new Gson().fromJson(response, OrderInfoBean.class);
                if (cartBean != null && cartBean.getData() != null) {
                    if (cartBean.getResult().equals("success")) {
                        OrderInfoBean.DataBean data = cartBean.getData();

                        //控制地址的显示 虚拟商品不显示地址，其他显示
                        if (data.getShops() != null && data.getShops().size() != 0) {
                            if (setAddressIsShow()) {
                                clAddress.setVisibility(View.GONE);
                            } else {
                                clAddress.setVisibility(View.VISIBLE);
                            }
                        }

                        allPrice = data.getGoodTotalMoney();
                        textViews.get(0).setText(ResStringUtil.getString(R.string.mail_common) + data.getGoodTotalCount() + ResStringUtil.getString(R.string.mail_piece_goods));
                        setPriceTotal();
                        List<OrderInfoBean.DataBean.ShopsBean> shops = data.getShops();
                        List<OrderInfoBean.DataBean.PreOrderDiscountBean> preOrderDiscount = data.getPreOrderDiscount();
                        if (preOrderDiscount != null && preOrderDiscount.size() > 0) {
                            orderRlvPre.setVisibility(View.VISIBLE);
                            mPres.clear();
                            mPres.addAll(preOrderDiscount);
                            preAdapter.notifyDataSetChanged(mPres);
                        } else {
                            orderRlvPre.setVisibility(View.GONE);
                        }
                        mShops.clear();
                        mShops.addAll(shops);
                        mAdapter.notifyDataSetChanged(mShops);

                        initAddress(null);

                    } else {
//                        ToastUtil.showToast(CreateOrderActivity.this, cartBean.getResult());
                    }

                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToast(CreateOrderActivity.this, getResources().getString(R.string.network_anomalies));
            }
        });
    }

    /**
     * 当提交的订单有多个店铺时，跳转我的订单页付款
     *
     * @param orders
     */
    private boolean showDialogPayHint(List<String> orders) {
        if (orders != null && orders.size() > 1) {
            DialogUtil.showDialogNoCancel(CreateOrderActivity.this, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //跳转未付款界面
                            Intent intent = new Intent(CreateOrderActivity.this, MallGeneralOrderActivity.class);
                            intent.putExtra("targetIndex", 1);
                            startActivity(intent);
                            finish();
                        }
                    }, R.string.dialog_title_defalut, getResources().getString(R.string.mall_create_order_confirm_pay_hint)
                    , getResources().getString(R.string.mall_create_order_go_pay));
            return true;
        }
        return false;
    }

    /**
     * 如果是虚拟商品就隐藏  显示
     */
    private boolean setAddressIsShow() {
        if (cartBean != null) {
            return cartBean.getData().getShowSelectAddress() == 0 ? true : false;
        } else {
            return false;
        }
    }
}
